#!/usr/bin/env python3
"""
Script to generate a mapping from crowdin_code to Django locale code.
Reads language_info.json and uses our copy of Django's locale utilities
to convert intl_code to locale format.
"""
import json
import os

from build_tools.i18n.utils import to_locale


def get_language_mapping():
    """
    Read language_info.json and return a mapping from crowdin_code to Django locale code.

    Returns:
        dict: Mapping from crowdin_code to locale code (underscore format)
    """
    # Get the path to language_info.json relative to this script
    script_dir = os.path.dirname(os.path.abspath(__file__))
    json_path = os.path.join(
        script_dir, "..", "..", "kolibri", "locale", "language_info.json"
    )

    with open(json_path, "r", encoding="utf-8") as f:
        languages = json.load(f)

    mapping = {}

    for lang in languages:
        crowdin_code = lang["crowdin_code"]
        intl_code = lang["intl_code"]

        # Use to_locale to convert intl_code to locale format
        # This handles script suffixes like 'hans' correctly
        locale_code = to_locale(intl_code)

        mapping[crowdin_code] = locale_code

    return mapping


def main():
    """Print the crowdin_code to locale code mapping in YAML format."""
    mapping = get_language_mapping()

    print("# Generated mapping from crowdin_code to Django locale code")  # noqa: T201
    print("# Generated by build_tools/i18n/generate_mapping.py")  # noqa: T201

    for crowdin_code, locale_code in sorted(mapping.items()):
        print(f'  "{crowdin_code}": "{locale_code}",')  # noqa: T201


if __name__ == "__main__":
    main()
